import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/motorcade_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_info_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_type_entity.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/custom_popup_menu_item.dart';
import 'package:nyh_motorcade_app/widgets/flexible_icon_text.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:nyh_motorcade_app/widgets/text_button_with_icon.dart';
import 'package:nyh_motorcade_app/widgets/text_with_icon.dart';
import 'package:nyh_motorcade_app/widgets/vehicle_icon.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'bind_vehicle_controller.dart';

class BindVehiclePage extends StatelessWidget {
  final controller = Get.put(BindVehicleController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.color_background,
      appBar: CustomAppBar(
        context: context,
        title: "绑定车辆",
        actions: [
          IconButton(
            onPressed: () {
              controller.goToAddVehiclePage();
            },
            icon: Image.asset("images/ic_add_vehicle.png"),
          ),
        ],
      ),
      body: GetBuilder<BindVehicleController>(
        builder: (controller) {
          return Column(
            children: [
              buildHeaderWidget(),
              buildListWidget(),
              buildConfirmWidget(),
            ],
          );
        },
      ),
    );
  }

  Widget buildHeaderWidget() {
    return Container(
      padding: EdgeInsets.only(left: 8.w, right: 16.w),
      height: 40.w,
      child: Row(
        children: [
          Expanded(
            child: Row(
              children: [
                TextButtonWithIcon(
                  onPressed: () {
                    showBelongToTypeMenu();
                  },
                  icon: Image.asset(controller.showBelongToTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                  label: Text(
                    controller.belongToName.isNotEmpty ? controller.belongToName : "车辆归属",
                    style: TextStyle(
                      color: Colours.color_text_theme,
                      fontSize: 14.sp,
                    ),
                  ),
                  textIconPadding: 5.w,
                  iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                ),
                SizedBox(
                  width: 5.w,
                ),
                TextButtonWithIcon(
                  onPressed: () {
                    showVehicleTypeMenu();
                  },
                  icon: Image.asset(controller.showVehicleTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                  label: Text(
                    controller.vehicleName.isNotEmpty ? controller.vehicleName : "全部车型",
                    style: TextStyle(
                      color: Colours.color_text_theme,
                      fontSize: 14.sp,
                    ),
                  ),
                  textIconPadding: 5.w,
                  iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                ),
                SizedBox(
                  width: 5.w,
                ),
                Flexible(
                  child: TextButtonWithIcon(
                    onPressed: () {
                      showMotorcadeMenu();
                    },
                    icon: Image.asset(controller.showMotorcadeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                    label: Text(
                      controller.motorcadeName.isNotEmpty ? controller.motorcadeName : "全部车队",
                      style: TextStyle(
                        color: Colours.color_text_theme,
                        fontSize: 14.sp,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    textIconPadding: 5.w,
                    iconTextAlignment: IconTextAlignment.iconRightTextLeft,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            width: 10.w,
          ),
          Text(
            "共${controller.orderCount}条",
            style: TextStyle(
              color: Colours.color_b7b7c0,
              fontSize: 14.sp,
            ),
          )
        ],
      ),
    );
  }

  Widget buildListWidget() {
    return Expanded(
      child: MultiStateWidget(
        child: SmartRefresher(
          controller: controller.refreshController,
          enablePullDown: true,
          enablePullUp: true,
          onRefresh: controller.onRefresh,
          onLoading: controller.onLoading,
          child: ListView.builder(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            itemCount: controller.vehicleInfoList.length,
            controller: controller.scrollController,
            itemBuilder: (context, index) {
              return buildItemWidget(index);
            },
          ),
        ),
        state: controller.multiState,
        onRetry: () {
          controller.onRetry();
        },
      ),
    );
  }

  Widget buildItemWidget(int index) {
    VehicleInfoItem entity = controller.vehicleInfoList[index];
    List<String> subCompanyList = entity.subCompanyList ?? [];
    List<String> quotaList = [];
    if (entity.refuelQuota != null) {
      quotaList.add("限额：${FormatUtils.formatMoney(entity.refuelQuota)}${entity.unit ?? ""}/${entity.circle ?? ""}");
    }
    if (entity.remainQuota != null) {
      quotaList.add("剩余：${FormatUtils.formatMoney(entity.remainQuota)}${entity.unit ?? ""}/${entity.circle ?? ""}");
    }
    bool isSelect = entity.isSelect ?? false;
    return Container(
      margin: EdgeInsets.only(left: 8.w, right: 16.w, bottom: 12.w),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              entity.isSelect = !isSelect;
              controller.update();
            },
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: isSelect ? Image.asset("images/ic_selected.png") : Image.asset("images/ic_unselect.png"),
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 8.w),
              decoration: BoxDecoration(
                color: Colours.color_white,
                borderRadius: BorderRadius.circular(10.w),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10.w),
                child: Material(
                  child: InkWell(
                    onTap: () {
                      entity.isSelect = !isSelect;
                      controller.update();
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 13.w, horizontal: 16.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          VehicleIcon(entity.type ?? "", entity.vehicleNumber ?? ""),
                          SizedBox(
                            width: 16.w,
                          ),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Flexible(
                                      child: Text(
                                        entity.vehicleNumber ?? "",
                                        style: TextStyle(
                                          color: Colours.color_text_theme,
                                          fontSize: 16.sp,
                                          fontWeight: FontWeight.bold,
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    Visibility(
                                      visible: (entity.belongToType ?? "").isNotEmpty,
                                      child: Container(
                                        margin: EdgeInsets.only(left: 8.w),
                                        padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                                        decoration: BoxDecoration(
                                          color: (entity.belongToType ?? "") == Constant.OWN_VEHICLE ? Colours.color_34c759 : Colours.color_theme,
                                          borderRadius: BorderRadius.circular(5.w),
                                          border: Border.all(
                                            width: 1.w,
                                            color: (entity.belongToType ?? "") == Constant.OWN_VEHICLE ? Colours.color_34c759 : Colours.color_theme,
                                          ),
                                        ),
                                        child: Text(
                                          entity.belongToTypeName ?? "",
                                          style: TextStyle(
                                            color: Colours.color_white,
                                            fontSize: 10.sp,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Visibility(
                                      visible: (entity.type ?? "").isNotEmpty,
                                      child: Container(
                                        margin: EdgeInsets.only(left: 8.w),
                                        padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                                        decoration: BoxDecoration(
                                          color: Colours.color_white,
                                          borderRadius: BorderRadius.circular(5.w),
                                          border: Border.all(width: 1.w, color: Colours.color_6f7082),
                                        ),
                                        child: Text(
                                          entity.typeName ?? "",
                                          style: TextStyle(
                                            color: Colours.color_6f7082,
                                            fontSize: 10.sp,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(
                                  height: (entity.motorcadeName ?? "").isNotEmpty ? 5.w : 0,
                                ),
                                Visibility(
                                  visible: (entity.motorcadeName ?? "").isNotEmpty,
                                  child: TextWithIcon(
                                    text: entity.motorcadeName ?? "",
                                    textStyle: TextStyle(
                                      color: Colours.color_6f7082,
                                      fontSize: 12.sp,
                                    ),
                                    iconName: "images/ic_motorcade.png",
                                    iconWidth: 14.w,
                                    iconHeight: 14.w,
                                    iconColor: Colours.color_6f7082,
                                    textIconPadding: 5.w,
                                  ),
                                ),
                                SizedBox(
                                  height: subCompanyList.isNotEmpty ? 5.w : 0,
                                ),
                                FlexibleIconText(
                                  icon: Image.asset(
                                    "images/ic_company.png",
                                    height: 14.w,
                                    width: 14.w,
                                    color: Colours.color_6f7082,
                                  ),
                                  textList: subCompanyList,
                                  iconTextPadding: 5.w,
                                ),
                                SizedBox(
                                  height: quotaList.isNotEmpty ? 5.w : 0,
                                ),
                                FlexibleIconText(
                                  textList: quotaList,
                                  textStyle: TextStyle(color: Colours.color_text_theme, fontSize: 12.sp),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildConfirmWidget() {
    return Visibility(
      visible: controller.vehicleInfoList.isNotEmpty,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
        decoration: BoxDecoration(
          color: Colours.color_white,
          boxShadow: [
            BoxShadow(
              color: Colours.color_0f112e_95,
              offset: Offset(0.0, -2.w),
              blurRadius: 5.w,
            ),
          ],
        ),
        child: TextButton(
          onPressed: () {
            controller.onConfirm();
          },
          child: Text(
            "确定",
            style: TextStyle(
              color: Colours.color_white,
              fontSize: 16.sp,
            ),
          ),
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.resolveWith((states) {
              return controller.getSelectVehicleIdList().isNotEmpty ? Colours.color_theme : Colours.color_ffd599;
            }),
            overlayColor: MaterialStateProperty.resolveWith((states) {
              return controller.getSelectVehicleIdList().isNotEmpty ? Colours.color_theme_deep : Colours.color_ffd599;
            }),
            shape: MaterialStateProperty.all(
              RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(28.w),
              ),
            ),
            minimumSize: MaterialStateProperty.all(Size(double.infinity, 48.w)),
          ),
        ),
      ),
    );
  }

  void showBelongToTypeMenu() {
    if (controller.belongToTypeList.isEmpty) {
      return;
    }
    controller.showBelongToTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(16.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.belongToTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.belongToTypeList[e].name)).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectBelongToType(value);
    });
  }

  Future<void> showVehicleTypeMenu() async {
    List<VehicleTypeEntity> list = await controller.getVehicleType();
    if (list.isEmpty) {
      return;
    }
    controller.showVehicleTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(100.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.vehicleTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.vehicleTypeList[e].dictdataName ?? "")).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectVehicleType(value);
    });
  }

  Future<void> showMotorcadeMenu() async {
    List<MotorcadeEntity> list = await controller.getMotorcadeList();
    if (list.isEmpty) {
      return;
    }
    controller.showMotorcadeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(200.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.motorcadeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.motorcadeList[e].name ?? "")).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectMotorcade(value);
    });
  }
}
